#include "common/http/HttpAgent.h"

#include <iostream>
using namespace std;

HttpAgent::HttpAgent(/* args */) {}

HttpAgent::HttpAgent(const SocketAddress &addr)
    : TCPAgent(addr)
    , response_(NULL)
{}

HttpAgent::~HttpAgent() {}

int HttpAgent::init()
{
    if (connect() != SUCCESSFUL) {
        cout << "init error" << endl;
        return FAILED;
    }
    return SUCCESSFUL;
}

int HttpAgent::connectAfter(bool bConnect)
{
    if (bConnect) {
        string line = "GET /version HTTP/1.1\r\nHost:127.0.0.1:2379\r\n\r\n";
        cout << "line:" << endl;
        cout << line << endl;
        sendPackage(line);
    }
    return SUCCESSFUL;
}

void HttpAgent::readBack(InReq &req)
{
    cout << "this is readBack" << endl;
    cout << req.ioBuf << endl;
}

int HttpAgent::sendPackage(std::string &data)
{
    unsigned int len = data.length();
    char *sendBuf = new char[len + 1];
    memset(sendBuf, 0, len + 1);
    memcpy(sendBuf, data.c_str(), data.size());
    writeToBuffer(sendBuf, len + 1);
    return SUCCESSFUL;
}

int HttpAgent::recvData()
{
    int ret = m_buffer.readTCPWithoutHeader(getID());
    if (ret < 0) {
        cout << "HttpAgent::recvData error" << endl;
        return FAILED;
    }
    return SUCCESSFUL;
}

string HttpAgent::getHost()
{
    std::string host = m_addr.getIP();
    host += ":";
    host += to_string(m_addr.getPort());
    return host;
}